//
//  FPBaseViewController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/15.
//

#import "FPBaseViewController.h"

@interface FPBaseViewController () <UIGestureRecognizerDelegate , DZNEmptyDataSetSource , DZNEmptyDataSetDelegate /* , CLLocationManagerDelegate */ , UIScrollViewDelegate>

@property (nonatomic , strong) UIButton *backBtn;

@property(strong , nonatomic) CLLocationManager *locationManager;



@property (nonatomic , assign) BOOL isCanSideBack;

@end

@implementation FPBaseViewController

- (void)setTableViewScrollEnable:(BOOL)tableViewScrollEnable {
    
    _tableViewScrollEnable = tableViewScrollEnable;
    
    self.tableView.scrollEnabled = _tableViewScrollEnable;
    self.group_tableView.scrollEnabled = _tableViewScrollEnable;
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    [self resetSideBack];
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

- (CustomPopOverView *)customPopView {
    
    if (!_customPopView) {
        
        _customPopView = [CustomPopOverView popOverView];
    }
    return _customPopView;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT-UIDevice.navigationFullHeight) style:(UITableViewStylePlain)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.tableFooterView = [UIView new];
        
//        if (UIDevice.safeDistanceTop == 20) {
//            
//            _tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);  // 64 是状态栏的高度
//            _tableView.scrollIndicatorInsets = _tableView.contentInset;
//        }
    }
    return _tableView;
}

- (UITableView *)group_tableView {
    
    if (!_group_tableView) {
        
        _group_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT-UIDevice.navigationFullHeight) style:(UITableViewStyleGrouped)];
        _group_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _group_tableView.showsVerticalScrollIndicator = NO;
        _group_tableView.emptyDataSetSource = self;
        _group_tableView.emptyDataSetDelegate = self;
        _group_tableView.tableFooterView = [UIView new];
        
//        if (UIDevice.safeDistanceTop == 20) {
//            
//            _group_tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);  // 64 是状态栏的高度
//            _group_tableView.scrollIndicatorInsets = _group_tableView.contentInset;
//        }
    }
    return _group_tableView;
}

LazyLoadDataSource(dataSource);

- (UIButton *)backBtn {
    
    if (!_backBtn) {
        
        _backBtn = [[UIButton alloc]initWithFrame:CGRectMake(12.f, UIDevice.statusBarHeight, 34, 44)];
        _backBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _backBtn;
}

- (UIButton *)closeBtn {
 
    if (!_closeBtn) {
        
        _closeBtn = [[UIButton alloc]initWithFrame:CGRectMake(12.f, UIDevice.statusBarHeight, 34, 44)];
        _closeBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
//        [_closeBtn setImage:IMG(@"icon_close") forState:(UIControlStateNormal)];
//        [_closeBtn setImage:IMG(@"icon_close") forState:(UIControlStateHighlighted)];
        _closeBtn.hidden = YES;
    }
    return _closeBtn;
}

- (UIWindow *)customWindow {
    
    if (!_customWindow) {
        
        _customWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _customWindow;
}

- (UIButton *)rightBtn {
    
    if (!_rightBtn) {
        
        _rightBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
//        [_rightBtn setImage:IMG(@"icon_home_sevice") forState:(UIControlStateNormal)];
        _rightBtn.frame = CGRectMake(SCREEN_WIDTH-12.f-24.f, UIDevice.statusBarHeight+10.f, 24.f, 24.f);
    }
    return _rightBtn;
}

- (UILabel *)titleLabel {
    
    if (!_titleLabel) {
        
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.adjustsFontSizeToFitWidth = YES;
    }
    return _titleLabel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    self.tableViewScrollEnable = YES;
    
    [self initUI];
}

- (void)initUI {
    
    // ...
}

- (void)setBackButtonStyleWhite:(BOOL)isWhite {
    
    if (isWhite) {
        
        [self.backBtn setImage:IMG(@"icon_nav_whiteBack") forState:UIControlStateNormal];
    }
    else {
        
        [self.backBtn setImage:IMG(@"icon_nav_blackBack") forState:UIControlStateNormal];
    }
}

- (void)setTitleStyleColor:(UIColor *)color {
    
    self.titleLabel.textColor = color;
}

- (void)showTableFooterNoMoreDataView {
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30.f)];
    lab.font = FONT(10.f);
    lab.textColor = [UIColor hexColor:@"#999999"];
    lab.text = @"没有更多啦~";
    lab.textAlignment = NSTextAlignmentCenter;
    self.tableView.tableFooterView = lab;
}

- (void)hideTableFooterNoMoreDataView {
    
    self.tableView.tableFooterView = [UIView new];
}

- (void)setTitle:(NSString *)title style:(XYCustomNavigationStyle)style hiddenBackBtn:(BOOL)hiddenBackBtn {
    
    self.style = style;
    self.navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, UIDevice.navigationFullHeight)];
    
//    if (IS_IPHONEX_SET) {
//
//        self.titleLabel.frame = CGRectMake(0, IPHONEX_StatusHeight-10.f, SCREEN_WIDTH, 44);
//    }
//    else {
//
//        self.titleLabel.frame = CGRectMake(0, IPHONEX_StatusHeight, SCREEN_WIDTH, 44);
//    }
    
    self.titleLabel.frame = CGRectMake(80.f, UIDevice.statusBarHeight, SCREEN_WIDTH-160.f, 44);
    self.titleLabel.text = title;
    self.titleLabel.font = BFONT(18);
    self.titleLabel.backgroundColor = UIColor.clearColor;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.navView addSubview:self.titleLabel];
    [self.navView addSubview:self.backBtn];
    [self.navView addSubview:self.closeBtn];
    
    if (style == XYCustomNavigationStyleBlack) { //黑色背景
        
        [self.backBtn setImage:IMG(@"icon_nav_whiteBack") forState:UIControlStateNormal];
        self.titleLabel.textColor = UIColor.whiteColor;
        self.navView.backgroundColor = UIColor.blackColor;
    }
    else if (style == XYCustomNavigationStyleClear) {
        
        [self.backBtn setImage:IMG(@"icon_nav_blackBack") forState:UIControlStateNormal];
        self.titleLabel.textColor = UIColor.blackColor;
        self.navView.backgroundColor = UIColor.clearColor;
    }
    else if (style == XYCustomNavigationStyleWhite) {
        
        [self.backBtn setImage:IMG(@"icon_nav_blackBack") forState:UIControlStateNormal];
        self.titleLabel.textColor = UIColor.blackColor;
        self.navView.backgroundColor = UIColor.whiteColor;
    }
    
    
    [self.navView bringSubviewToFront:self.closeBtn];
    [self setNeedsStatusBarAppearanceUpdate];
    
    self.backBtn.hidden = hiddenBackBtn;
    
    [self.view addSubview:self.navView];
    [self.backBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        
//        [self.navigationController popViewControllerAnimated:YES];
        [self backAction];
    }];
}

- (void)setRightButton {
    
    [self.navView addSubview:self.rightBtn];
    
//    if (self.style == XYCustomNavigationStyleGradualLengthen || self.style == XYCustomNavigationStyleGradualLengthenMax) {
//
//        self.rightBtn.top = IPHONEX_StatusHeight + 10.f;
//    }
    
    [self.rightBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
            
        [self rightButtonAction];
    }];
}

- (void)rightButtonAction {
    
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    if (self.style == XYCustomNavigationStyleWhite || self.style == XYCustomNavigationStyleClear /*|| self.style == XYCustomNavigationStyleB3Product */) {
        
        return UIStatusBarStyleDarkContent;
    }
    else if (self.style == XYCustomNavigationStyleBlack) {
        
        return UIStatusBarStyleLightContent;
    }
//    else if (self.style == XYCustomNavigationStyleGradual || self.style == XYCustomNavigationStyleGradualLengthen || self.style == XYCustomNavigationStyleGradualLengthenMax) {
//    
//        return UIStatusBarStyleLightContent;
//    }
    
    return UIStatusBarStyleLightContent;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)hiddenLeftCloseButton:(BOOL)hidden {
    
    self.closeBtn.hidden = hidden;
}


#pragma mark - 没有数据处理
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    return IMG(@"");//[UIImage imageNamed:@"no_data"];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {

    return - 80.f;
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {

    NSString *text = @"";

    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [NSString stringToAttribute:attStr font:FONT(16.f) range:NSMakeRange(0, text.length)];
    [NSString stringToAttribute:attStr color:[UIColor hexColor:@"#999999"] range:NSMakeRange(0, text.length)];

    return attStr;
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    
//    [self showText:@"刷新中。。。"];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self.tableView || scrollView == self.group_tableView) {
    
        if (self.tableViewScrollEnable == NO) {
            
            // 禁用滑动
            if (scrollView == self.tableView) {
            
                CGFloat offsetY = scrollView.contentOffset.y;
                
                if (offsetY <= -1.f) {
                 
                    offsetY = 0.f;
                    self.tableView.contentOffset = CGPointMake(0.f, 0.f);
                }
                else if (offsetY >= 0.f) {
                 
                    offsetY = 0.f;
                    self.tableView.contentOffset = CGPointMake(0.f, 0.f);
                }
            }
        }
        else {
         
            CGFloat offsetY = scrollView.contentOffset.y;
            
            // 最多下滑到table view 的background view的高度
            if (offsetY <= -200.f) {
             
                offsetY = 0.f;
                self.tableView.contentOffset = CGPointMake(0.f, -200.f);
                self.group_tableView.contentOffset = CGPointMake(0.f, -200.f);
            }
            
            // 上滑透明导航栏
    //        if (offsetY == 0) {
    //
    //            self.navToolsView.alpha = 1.f;
    //        }
    //        else {
    //
    //            if (offsetY > 0) {
    //
    //                self.navToolsView.alpha = 1 - offsetY/IPHONEX_NavigationBarHeight;
    //            }
    //            else {
    //
    //                self.navToolsView.alpha = 1.f;
    //            }
    //        }
        }
    }
}

# pragma mark - 是否拥有定位权限
- (CLLocationManager *)locationManager {
    
#warning 暂时没有定位
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
//        _locationManager.delegate = self;
//        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//        _locationManager.distanceFilter = kCLDistanceFilterNone;
//        [_locationManager requestAlwaysAuthorization];
    }
    return _locationManager;
}

//当前定位状态是否可用
- (BOOL)locationAuthStatusIsValid {

    if ([self locationServiceIsValid] == NO) {

        return NO;
    }

    if ([self authorizationStatus] == kCLAuthorizationStatusNotDetermined) {

        return NO;
    }

    return YES;
}

//当前应用是否可以使用/申请定位服务
- (BOOL)locationServiceIsValid {
    
    if ([self authorizationStatus] == kCLAuthorizationStatusDenied ||
        
        [self authorizationStatus] == kCLAuthorizationStatusRestricted) {
        
        return NO;
    }
    
    return YES;
    
}

//获取当前定位权限
- (CLAuthorizationStatus)authorizationStatus {

//    return [CLLocationManager authorizationStatus];
    if (@available(iOS 14.0, *)) {

        return self.locationManager.authorizationStatus;

    } else {

        return [CLLocationManager authorizationStatus];

    }
}


# pragma mark - 弹出window 可以在这个window上添加view
- (void)showWindowCanTapHidden:(BOOL)canHidden {
    
    self.customWindow.rootViewController = [UIViewController new];
    self.customWindow.rootViewController.view.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:.6f];
    self.customWindow.rootViewController.view.userInteractionEnabled = NO;
    
    if (canHidden) {
     
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideWindow)];
        [self.customWindow addGestureRecognizer:tap];
        tap.delegate = self;
    }
    
    //设置为最顶层，防止 AlertView 等弹窗的覆盖
    self.customWindow.windowLevel = UIWindowLevelStatusBar + 1;
    self.customWindow.hidden = NO;
    
    self.customWindow.alpha = 0.f;
    
    [UIView animateWithDuration:.25f animations:^{
        
        [self.customWindow setAlpha:1.f];
        
    } completion:^(BOOL finished) { }];
}

- (void)hideWindow {
    
    [UIView animateWithDuration:.25f animations:^{
        
        [self.customWindow setAlpha:0.f];
        
    } completion:^(BOOL finished) {
        
        self.customWindow.hidden = YES;
        self.customWindow = nil;
    }];
}

- (void)showText:(NSString *)text {
    
    [self.customPopView showTextOnCustomView:text afterDelay:1.5f];
}
- (void)showText:(NSString *)text afterDelay:(NSTimeInterval)afterDelay {
    
    [self.customPopView showTextOnCustomView:text afterDelay:afterDelay];
}
- (void)showError:(NSError *)error {
    
    [MBManager showError:error];
}
- (void)hideLoading {
    
    [self.customPopView dismiss];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    if ([touch.view isEqual:self.customWindow.subviews]) {
        
        return NO;
    }
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    
    return UIInterfaceOrientationMaskPortrait;
}

- (void)forbiddenSideBack {

    self.isCanSideBack = NO;
    
    //关闭ios右滑返回
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {

        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)resetSideBack {

    self.isCanSideBack = YES;

    //开启ios右滑返回
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {

        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer {

    return self.isCanSideBack;
}



#pragma mark - 签署协议
- (void)signProtocolWithParams:(NSMutableArray *)params {
    
    NSMutableArray *temp = NSMutableArray.array;
    
    for (NSUInteger i = 0; i < params.count; i ++) {
        
        FPProtocolModel *model = params[i];
        
        NSMutableDictionary *dic = NSMutableDictionary.dictionary;
        
        [dic setValue:model.address forKey:@"agreementAddress"];
        [dic setValue:model.ID forKey:@"agreementId"];
        [dic setValue:FPUserInfoModel.sharedUserInfo.idcardNumber forKey:@"idNumber"];
        [dic setValue:FPUserInfoModel.sharedUserInfo.idcardName forKey:@"userName"];
        [dic setValue:model.status forKey:@"status"];
        
        NSString *number = [FPUserModel AES256Encrypt:FPUserInfoModel.sharedUserInfo.phone];
        [dic setValue:number forKey:@"userPhone"];
        
        [temp addObject:dic];
    }
    
    [FPProtocolModel protocolSignWithParams:temp success:^(NSInteger code, NSString * _Nonnull message) {
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

@end

